<template>
	<view class="template-order">
		<!-- 顶部自定义导航 -->
		<tn-nav-bar :bottomShadow="false" backgroundColor="#FFFFFF" customBack fixed>
			<view slot="back" class='tn-custom-nav-bar__back' @click="goBack">
				<text class='icon tn-icon-left-arrow'></text>
			</view>
			<view class="tn-flex tn-flex-col-center tn-flex-row-center ">
				<text class="tn-text-bold tn-text-xl tn-color-black">子订单</text>
			</view>
		</tn-nav-bar>

		<view :style="{top: vuex_custom_bar_height + 20 +'px'}" class="order--wrap" :key="componentKey">
			<!-- 顶部标签 -->
			<view class="tn-bg-white">
				<tn-tabs-swiper ref="tabs" :current="tabsIndex" :isScroll="false" :list="list" activeColor="#3165CC"
					class="order__tabs tn-text-xl" inactiveColor="#080808" @change="tabsChange"></tn-tabs-swiper>
			</view>

			<!-- 标签内容 -->
			<swiper :current="swiperIndex" :style="{top: 60 +'px', height: `${swiperHeight}px`}"
				class="order__swiper" @animationfinish="swiperAnimationFinish" @transition="swiperTransition">
				<block v-for="(item,index) in resultList" :key="index">
					<swiper-item class="order__swiper__item">
						<scroll-view scroll-y v-if="item.length > 0" :style="{height: `${swiperHeight}px`}">
							<view v-for="e in item" :key="e.id" class="order__item">
								<!-- 修改为左右两栏布局 -->
								<view class="order__item__container tn-flex tn-flex-direction-row tn-flex-nowrap tn-flex-col-center tn-flex-row-between">
									<!-- 左侧栏：订单编号、商品标题、创建时间 -->
									<view class="order__item__left tn-flex tn-flex-direction-column tn-flex-col-top">
										<!-- 订单编号 -->
										<view class="order__item__left__order-id" @click.stop="copyFun(e.orderId)">
											<text class="tn-text-bold">订单编号：{{ e.id }}</text>
											<text class="tn-color-blue--disabled tn-padding-left-xs tn-text-df tn-icon-copy"></text>
										</view>
										
										<!-- 商品标题 -->
										<view class="order__item__left__title tn-margin-top-sm">
											{{ e.title }}
										</view>
										
										<!-- 创建时间 -->
										<view class="order__item__left__time tn-margin-top-sm">
											<text class="tn-color-gray">{{formatTime(e.createTime)}}</text>
										</view>
									</view>
									
									<!-- 右侧栏：订单状态、价格、按钮 -->
									<view class="order__item__right tn-flex tn-flex-direction-column tn-flex-col-center tn-flex-row-right">
										<!-- 订单状态 -->
										<view class="order__item__right__status">
											<tn-tag :backgroundColor="`tn-main-gradient-${getBgColor(e.orderPayStatus)}--light`"
												:fontColor="`tn-color-${getFontColor(e.orderPayStatus)}`" shape="circle"
												height="48rpx" width="100">
												{{getText(e.orderPayStatus)}}
											</tn-tag>
										</view>
										
										<!-- 价格 -->
										<view class="order__item__right__price tn-margin-top-sm">
											<text class="order__item__right__price--unit">￥</text>
											<text class="order__item__right__price--integer">{{ e.totalPrice }}</text>
										</view>
										
										<!-- 操作按钮 -->
										<view class="order__item__right__button tn-margin-top-sm">
											<!-- 根据订单状态显示不同按钮 -->
											<tn-button v-if="e.orderPayStatus === 1" backgroundColor="#3165CC" fontColor="#FFFFFF" 
												@click.stop="goToPay(e)" shape="round" padding="18rpx 30rpx" width="160rpx">
												去支付
											</tn-button>
											<tn-button v-if="e.orderPayStatus === 2" backgroundColor="#3165CC" fontColor="#FFFFFF" 
												@click.stop="confirmReceive(e)" shape="round" padding="18rpx 30rpx" width="180rpx">
												确认收货
											</tn-button>
										</view>
									</view>
								</view>
							</view>
							<view class="tn-padding-bottom"></view>
						</scroll-view>
						<view v-else>
							<tn-empty mode="order"></tn-empty>
						</view>
					</swiper-item>
				</block>
			</swiper>
		</view>


	</view>
</template>

<script>
	import templatePageMixin from '@/libs/mixin/template_page_mixin.js'
	import {
		getSubOrderStatusList
	} from "@/api/user";
	import {
		getPayURL
	} from "@/api/pay";

	export default {
		name: 'TemplateOrder',
		mixins: [templatePageMixin],
		data() {
			return {
				list: [{
						name: '全部'
					},
					{
						name: '待支付'
					},
					{
						name: '待交付'
					},
					{
						name: '已结束'
					}
				],
				componentKey: 0,
				tabsIndex: 0,
				swiperIndex: 0,
				swiperTop: 20,
				swiperHeight: 0,
				resultList: [],
				orderStatus: global.staticDict.subOrderStatus
			}
		},
		onLoad(param) {
			this.type = param.type
		},
		async onShow() {
			await this.queryOrderStatusList(this.type)
			this.swiperIndex = this.tabsIndex
			this.componentKey++;
		},
		onReady() {
			this.$nextTick(() => {
				this.updateSwiperInfo()
			})
			this.tabsIndex = this.type
		},
		computed: {},
		methods: {
			// 去支付
			goToPay(item) {
				this.tn(`/minepages/paymentOrder?id=${item.id}`)
			},
			// 确认收货
			confirmReceive(item) {
				uni.showModal({
					title: '提示',
					content: '确认已收到商品？',
					success: (res) => {
						if (res.confirm) {
							// 这里可以调用确认收货的API
							uni.showLoading({
								title: '处理中...'
							})
							// 模拟API调用
							setTimeout(() => {
								uni.hideLoading()
								uni.showToast({
									title: '确认收货成功',
									icon: 'success'
								})
								// 刷新订单列表
								this.queryOrderStatusList(this.type)
							}, 1000)
						}
					}
				})
			},
			copyFun(orderCode) {
				uni.setClipboardData({
					data: orderCode,
				})
			},
			goBack(){
				uni.navigateBack()
			},
			//标签背景颜色
			getBgColor(status = 1) {
				return this.orderStatus[status].bgColor
			},
			//标签字体颜色
			getFontColor(status = 1) {
				return this.orderStatus[status].color
			},
			//标签文本
			getText(status = 1) {
				return this.orderStatus[status].text
			},
			// 格式化时间为年月日格式
			formatTime(timeString) {
				if (!timeString) return '';
				try {
					// 将 "2025-07-27 14:22:13" 转换为 "2025年07月27日 14:22:13"
					const parts = timeString.split(' ');
					if (parts.length >= 1) {
						const datePart = parts[0]; // "2025-07-27"
						const timePart = parts[1] || ''; // "14:22:13"

						const dateArray = datePart.split('-');
						if (dateArray.length === 3) {
							const year = dateArray[0];
							const month = dateArray[1];
							const day = dateArray[2];

							const formattedDate = `${year}年${month}月${day}日`;
							return timePart ? `${formattedDate} ${timePart}` : formattedDate;
						}
					}
					return timeString; // 如果格式不对，返回原字符串
				} catch (e) {
					return timeString;
				}
			},
			async queryOrderStatusList(type) {
				try {
					// 子订单状态映射：全部、待支付、待交付(已付款)、已结束
					const temp = ['status_all', 'status_wait_pay', 'paid', 'status_end']

					// 调用真实的子订单API
					for (const item of temp) {
						const res = await getSubOrderStatusList(item)
						if (res.code === 200) {
							this.resultList[temp.indexOf(item)] = res.data || []
						} else {
							uni.showToast({
							  title: "系统异常",
							  duration: 1500,
							  icon: 'error'
							});
							this.resultList[temp.indexOf(item)] = []
						}
					}
				} catch (e) {
					console.log('查询子订单列表失败:', e)
					uni.showToast({
					  title: "查询失败",
					  duration: 1500,
					  icon: 'error'
					});
				}
			},
			// 跳转
			tn(e) {
				uni.navigateTo({
					url: e,
				});
			},

			// 计算可滑动区域的高度信息
			updateSwiperInfo() {
				// 获取可滑动菜单的信息
				this._tGetRect('.order__tabs').then(res => {
					if (!res) {
						setTimeout(() => {
							this.updateSwiperInfo()
						}, 10)
						return
					}
					const systemInfo = uni.getSystemInfoSync()
					this.swiperTop = res.bottom - this.vuex_custom_bar_height
					this.swiperHeight = systemInfo.safeArea.height - res.bottom + systemInfo.statusBarHeight
				})
			},
			// 标签栏值发生改变
			tabsChange(index) {
				this.swiperIndex = index
			},
			// swiper-item位置发生改变
			swiperTransition(event) {
				this.$refs.tabs.setDx(event.detail.dx)
			},
			// swiper动画结束
			swiperAnimationFinish(event) {
				const current = event.detail.current
				this.$refs.tabs.setFinishCurrent(current)
				this.swiperIndex = current
				this.tabsIndex = current
			}
		}
	}
</script>

<style lang="scss" scoped>
	.template-order {
		background-color: #FFFFFF;
	}

	/* 胶囊*/
	.tn-custom-nav-bar__back {
		width: 60%;
		height: 100%;
		position: relative;
		display: flex;
		justify-content: space-evenly;
		align-items: center;
		box-sizing: border-box;
		background-color: rgba(0, 0, 0, 0.15);
		border-radius: 1000rpx;
		border: 1rpx solid rgba(255, 255, 255, 0.5);
		color: #FFFFFF;
		font-size: 18px;

		.icon {
			display: block;
			flex: 1;
			margin: auto;
			text-align: center;
		}

	}

	.order {
		&--wrap {
			position: fixed;
			left: 0;
			right: 0;
			width: 100%;
			background-color: inherit;
		}

		/* 导航栏 start */
		&__tabs {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			background-color: inherit;
		}

		/* 导航栏 end */

		/* swiper start */
		&__swiper {
			position: absolute;
			left: 0;
			right: 0;
			width: 100%;
			background-color: inherit;
			// padding: 0 16rpx;
		}

		/* swiper end */

		/* 订单内容 start */
		&__item {
			margin: 30rpx;
			padding: 36rpx 26rpx;
			background-color: #FFFFFF;
			border-radius: 15rpx;
			box-shadow: 0rpx 0rpx 50rpx 0rpx rgba(0, 0, 0, 0.07);

			&:first-child {
				margin-top: 40rpx;
			}

			&:last-child {
				margin-bottom: 0;
			}
			
			/* 左右两栏容器 */
			&__container {
				width: 100%;
			}
			
			/* 左侧栏 */
			&__left {
				flex: 1;
				padding-right: 20rpx;
				
				&__order-id {
					line-height: normal;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					display: flex;
					align-items: center;
				}
				
				&__title {
					display: -webkit-box;
					overflow: hidden;
					white-space: normal !important;
					text-overflow: ellipsis;
					word-wrap: break-word;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
				}
			}
			
			/* 右侧栏 */
			&__right {
				min-width: 180rpx;
				
				&__price {
					&--unit {
						font-size: 20rpx;
					}
					
					&--integer {
						font-weight: bold;
					}
				}
			}
		}

		/* 订单内容 end */
	}
</style>